import json
import time

import grpc

import nacos_grpc_service_pb2 as nacos_pb2
import nacos_grpc_service_pb2_grpc as nacos_grpc


def wrap_data(data):
    json_data = json.dumps(data)
    bytes_data = json_data.encode('utf-8')
    body = {
        "value": bytes_data
    }
    return body


def stream_payload():
    meta = nacos_pb2.Metadata(type="ConnectionSetupRequest", clientIp="172.17.155.17")
    data = {
        'headers': {},
        'clientVersion': 'Nacos-Java-Client:v2.2.1',
        'abilities': {
            'remoteAbility': {
                'supportRemoteConnection': True
            },
            'configAbility': {
                'supportRemoteMetrics': True
            },
            'namingAbility': {
                'supportDeltaPush': False,
                'supportRemoteMetric': False
            }
        },
        'tenant': '',
        'labels': {
            'module': 'config',
            'source': 'sdk',
            'taskId': '0',
            'AppName': 'unknown'
        },
        'module': 'internal'
    }
    body = wrap_data(data)
    payload = nacos_pb2.Payload(metadata=meta, body=body)
    yield payload


def main_process():
    channel = grpc.insecure_channel('localhost:9848')  # 9848 = 8848 + 1000
    request_stub = nacos_grpc.RequestStub(channel)

    # server check
    meta = nacos_pb2.Metadata(type="ServerCheckRequest", clientIp="172.17.155.17")
    data = {'headers': {}, 'module': 'internal'}
    body = wrap_data(data)
    payload = nacos_pb2.Payload(metadata=meta, body=body)
    response = request_stub.request(payload)
    print("server_check response:\n" + str(response))

    # connection setup
    bi_stub = nacos_grpc.BiRequestStreamStub(channel)
    response = bi_stub.requestBiStream(stream_payload())
    time.sleep(1)
    print("connection_setup response:\n" + str(response))

    # get/query config
    meta = nacos_pb2.Metadata(type="ConfigQueryRequest", clientIp="172.17.155.17")
    data = {
        'headers': {},
        'dataId': 'cyh-test-01',
        'group': 'DEFAULT_GROUP',
        'tenant': '',
        'notify': False,
        'module': 'config'
    }
    body = wrap_data(data)
    payload = nacos_pb2.Payload(metadata=meta, body=body)
    response = request_stub.request(payload)
    print("query_config response:\n" + str(response))


if __name__ == '__main__':
    main_process()
